package com.cookor.poi.modules.sys.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cookor.poi.common.config.Global;
import com.cookor.poi.common.web.BaseController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping(value = "${adminPath}/fileupload")
public class FileUploadController extends BaseController {

    @Value("${userfiles.basedir}")
    private String save_path;

    private String allowSuffix = Global.getAllowUploadSuffix();//允许文件格式
    private long allowSize = Long.valueOf(Global.getMaxUploadSize());//允许文件大小
    private String fileName;
    private String[] fileNames;
    public String getAllowSuffix() {
        return allowSuffix;
    }
    public void setAllowSuffix(String allowSuffix) {
        this.allowSuffix = allowSuffix;
    }
    public long getAllowSize() {
        return allowSize;//*1024*1024;
    }
    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public String[] getFileNames() {
        return fileNames;
    }
    public void setFileNames(String[] fileNames) {
        this.fileNames = fileNames;
    }
    private String getFileNameNew(){
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }
    public void uploads(MultipartFile[] files, String destDir,HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
        try {
            fileNames = new String[files.length];
            int index = 0;
            for (MultipartFile file : files) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
                int length = getAllowSuffix().indexOf(suffix);
                if(length == -1){
                    throw new Exception("请上传允许格式的文件");
                }
                if(file.getSize() > getAllowSize()){
                    throw new Exception("您上传的文件大小已经超出范围");
                }
//                String realPath = request.getSession().getServletContext().getRealPath("/");
                File destFile = new File(save_path+destDir);
                if(!destFile.exists()){
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew()+"."+suffix;//
                File f = new File(destFile.getAbsoluteFile()+"\\"+fileNameNew);
                file.transferTo(f);
                f.createNewFile();
                fileNames[index++] =basePath+destDir+fileNameNew;
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public void upload(MultipartFile file, String destDir,HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            int length = getAllowSuffix().indexOf(suffix);
            if(length == -1){
                throw new Exception("请上传允许格式的文件");
            }
            if(file.getSize() > getAllowSize()){
                throw new Exception("您上传的文件大小已经超出范围");
            }

//            String realPath = request.getSession().getServletContext().getRealPath("/");
            File destFile = new File(save_path+destDir);
            if(!destFile.exists()){
                destFile.mkdirs();
            }
            String fileNameNew = getFileNameNew()+"."+suffix;
            File f = new File(destFile.getAbsoluteFile()+"/"+fileNameNew);
            file.transferTo(f);
            f.createNewFile();
            fileName = basePath+destDir+fileNameNew;
        } catch (Exception e) {
            throw e;
        }
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response){
        try {
            String uploadType = request.getParameter("uploadType");
            logger.info("uploadType="+uploadType);
            upload(file, Global.USERFILES_BASE_URL,request);
            response.getWriter().print(getFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
